class Solution
{
public:
    string decodeString(const string &s)
    {
        return decodeString(s, 0, s.size());
    }

    string decodeString(const string &s, int start, int end)
    {
        if (start >= end)
        {
            return "";
        }
        int leftbracket = 0;
        int leftStart = 0;
        int repeatCount = 0;
        string result;
        int i = start;
        while (i < end)
        {
            if (leftbracket == 0 && s[i] >= 'a' && s[i] <= 'z')
            {
                result += s[i];
                ++i;
            }
            else if (leftbracket == 0 && s[i] >= '1' && s[i] <= '9')
            {
                int numLen = 1;
                while (i + numLen < end && s[i + numLen] >= '0' && s[i + numLen] <= '9')
                {
                    ++numLen;
                }
                repeatCount = stoi(s.substr(i, numLen));
                ++leftbracket;
                leftStart = i + numLen;
                i += numLen + 1;
            }
            else
            {
                if (s[i] == '[')
                {
                    ++leftbracket;
                }
                else if (s[i] == ']')
                {
                    --leftbracket;
                    if (leftbracket == 0)
                    {
                        string subDecoded = decodeString(s, leftStart + 1, i);
                        for (int j = 0; j < repeatCount; ++j)
                        {
                            result += subDecoded;
                        }
                    }
                }
                ++i;
            }
        }
        return result;
    }
};